package test.io;

import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.util.zip.Checksum;

/**
 * 经测算，crc32的耗时比md5慢一倍，如果一起算crc32和md5的话，大概耗时为md5的耗时<br>
 * 
 * @author yuqih
 * @see java.util.zip.CheckedInputStream
 */
public class DigestInputStream extends FilterInputStream {
	private Checksum cksum;
	private MessageDigest digest;

	public DigestInputStream(InputStream in, Checksum cksum,
			MessageDigest digest) {
		super(in);
		this.cksum = cksum;
		this.digest = digest;
	}

	@Override
	public int read() throws IOException {
		int b = in.read();
		if (b != -1) {
			if (cksum != null) {
				cksum.update(b);
			}
			if (digest != null) {
				digest.update((byte) b);
			}
		}
		return b;
	}

	@Override
	public int read(byte[] buf, int off, int len) throws IOException {
		len = in.read(buf, off, len);
		if (len != -1) {
			if (cksum != null) {
				cksum.update(buf, off, len);
			}
			if (digest != null) {
				digest.update(buf, off, len);
			}
		}
		return len;
	}

	@Override
	public long skip(long n) throws IOException {
		byte[] buf = new byte[512];
		long total = 0;
		while (total < n) {
			long len = n - total;
			len = read(buf, 0, len < buf.length ? (int) len : buf.length);
			if (len == -1) {
				return total;
			}
			total += len;
		}
		return total;
	}

	public Checksum getChecksum() {
		return cksum;
	}

	/**
	 * @return the digest
	 */
	public MessageDigest getDigest() {
		return digest;
	}

}
